<?php
// +----------------------------------------------------------------------
// | ThinkSNS
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://www.thinksns.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: nonant <nonant@thinksns.com>
// +----------------------------------------------------------------------
//

//动态服务
class NotifyService extends Service{
    public function __construct($data) {
		//2.服务初始化
		$this->run();
    }


	//运行服务，系统服务自动运行
	public function run(){

	}


	/**
	 +----------------------------------------------------------
	 * Description 添加通知
	 +----------------------------------------------------------
	 * @author Nonant nonant@thinksns.com
	 +----------------------------------------------------------
	 * @param String     $type   通知类型
	 * @param String     $touid   用户的ID
	 * @param String     $title  通知标题
	 * @param String     $body   通知内容
	 +----------------------------------------------------------
	 * @return int 结果
	 +----------------------------------------------------------
	 * Create at  2010-1-19 下午06:48:41
	 +----------------------------------------------------------
	 */
	public function put($type,$touid,$title,$body,$uid='',$fid=0){
		if(!$touid){
			return false;
		}
		$temp = $title;
		$app = explode('_',$type);
		$uid        = ($uid)?$uid:$_SESSION['mid'];

		$title      = addslashes(serialize( $title ));
		$body       = addslashes(serialize( $body ));
		$fid        = 0;
		$appname    = $app[0];
		$ctime      = time();
		if(strpos($touid,',') !== false){
			foreach (array_unique(explode(',',$touid)) as $key=>$value){
				if($uid!=$value) $sendto[] = $value;
			}
		}else{
			if($uid!=$touid) $sendto[] = $touid;
		}
		$_template = require SITE_PATH.'/public/language/'.getLang().'/notifys.php';
		$service = service("Mail");
		foreach ($sendto as $k=>$v){
			if( in_array($type,D('SpaceSetting','home')->get_User_Setting($v,'notify')) ||  $_template[$type]['private']==true){
				$arr[]="($uid,$v,'$type','$title','$body',$ctime,'$appname',0,$fid)";
			}
			if(in_array($type,D('SpaceSetting','home')->get_User_Setting($v,'email'))){	
				$sendUser = "";			
				$sendUser = getUserEmail($v);
				$senderInfo = array(
				   'name' => getUserName($uid),
				   'email'=> getUserEmail($uid),
				);
				$data['app'] = $app;
				$data['uid'] = $uid;
				$data['title'] = $title;
				$data['body']  = $body;
				$data['fid']   = 0;
				$data['appname'] = $appname;
				$data['cTime']   = $ctime;
				$data['touid']   = $v;
				$data['type']    = $type;
				$aData = $this->__paseTemplate($data);
				$temp['title'] = preg_replace("/<span class=\"(\w+)\">\d+<\/span>/i","",$temp['title']);
				$aTitle = "hi:".sprintf($aData['email'],$senderInfo['name'],t($temp['title']));

				$aBody   = $this->__getEmailBody($aData,$senderInfo['name'],$uid);
				$result = $service->send_email($sendUser,$aTitle,$aBody,$senderInfo);
			}
		}
		

		if($arr){
			$sqlvalue = implode(',',$arr);
			$result = D('Notify')->query("INSERT INTO ".C('DB_PREFIX')."notify (uid,touid,type,title,body,cTime,appname,isread,fid) values $sqlvalue");
			//dump(D('Notify')->getLastSql());
			return $result;
		}
		
 	}


	/**
	 +----------------------------------------------------------
	 * Description 搜索指定条件下的结果，并返回最终的模板渲染结果
	 +----------------------------------------------------------
	 * @author Nonant nonant@thinksns.com
	 +----------------------------------------------------------
	 * @param int $uid 用户ID
	 +----------------------------------------------------------
	 * @return array
	 +----------------------------------------------------------
	 * Create at  2010-1-19 下午06:46:54
	 +----------------------------------------------------------
	 */
	public function get($map,$limit=10){

		$feedlist = M('Notify')->where($map)->order('cTime DESC')->field('id,title,toUid,uid,body,cTime,type,fid,appname')->findPage($limit);

		//取出用户名
		foreach($feedlist['data'] as $value){
			$user[] = $value['uid'];
		}

		$userMap['uid'] = array('in',$user);
		$userDao = model('User');
		$user = $userDao->where($userMap)->field('uid,fullname')->findAll();

		$feedlist['data'] = arrayJoin($feedlist['data'],$user,'uid');

		foreach ($feedlist['data'] as $key=>&$value){
			$parseData = $this->__paseTemplate($value);
			$value['title']    = $parseData['title'];
			$value['body']     = $parseData['body'];
			$value['comment']  = $parseData['comment'];
		}
		return $feedlist;
	}



	/**
	 +----------------------------------------------------------
	 * Description 解析动态模版标签
	 +----------------------------------------------------------
	 * @author Nonant nonant@thinksns.com & Sam penglingjun@thinksns.com修改
	 +----------------------------------------------------------
	 * @param string $type 动态类型
	 * @param array  $data 动态的原始数据
	 +----------------------------------------------------------
	 * @return array
	 +----------------------------------------------------------
	 * Create at  2010-1-19 下午06:44:46
	 +----------------------------------------------------------
	 */
	protected function __paseTemplate($aData){
		if( false == $_title = unserialize($aData['title'])){
			$_title = unserialize(stripslashes($aData['title']));
		}
		
		if( false == $_body  = unserialize($aData['body'])){
			$_body = unserialize(stripslashes($aData['body']));
		}

		$_type  = $aData['type'];
        // 自定义变量替换
        $app_url      = SITE_URL."/index.php?app=".$aData['appname'];
		$actor_name   = $aData['fullname'];// 站点公共目录
        $actor        = "<a style='white-space: nowrap;' href='".U('space/View/index',array('uid'=>$aData["uid"]))."'>".$actor_name.'</a>';
        $actor_uid    = $aData['uid'];// 站点公共目录
        $_var = "";

        if(is_array($_title)){
	        foreach ($_title as $k=>$v){
	        	$$k = $v;
	        	$_var .= "\${$k} = \"{$v}\";";
	        }
        }


        if(is_array($_body)){
	        foreach ($_body as $k=>$v){
	        	$$k = $v;
				$_var .= "\${$k} = \"{$v}\";";
	        }
        }
        $_template = require SITE_PATH.'/public/language/'.getLang().'/notifys.php';
        $aData['body']     = $_template[$_type]['body'];
        $aData['title']    = $_template[$_type]['title'];
        $aData['info']     = $_template[$_type]['info'];
		$aData['comment']  = ($_template[$_type]['comment_type'])?W('Comment',array('type'=>$_template[$_type]['comment_type'],'fid'=>$aData['fid']),true):'';
		$aData['email']    = $_template[$_type]['email'];
		
		return $aData;
	}
	
	public function __getEmailBody($data,$uname,$uid){
//		$aBody   = $data['title'].'<br />'.$data['body'];
		$data['title'] = preg_replace("/<span class=\"(\w+)\">\d+<\/span>/i","",$data['title']);
		$path = SITE_URL;
		$url = U('space/view/index','uid='.$uid);
		$temp_html = <<<EOT
<div style="color:#000;font-size:12px;">
Dear:<br />
&nbsp;&nbsp;&nbsp;&nbsp;{$data['title']}

<div style="margin-left: 30px;">
{$data['body']}
</div>
<a href="{$url}">{$uname}</a><br />

=============================================================================<br />
&nbsp;&nbsp;&nbsp;&nbsp;“热爱分享，畅想成长”<br />
&nbsp;&nbsp;&nbsp;&nbsp;知识共享平台：<a href="{$path}">{$path}</a><br />
=============================================================================
</div>
EOT;
		$aBody = $temp_html;
		$aBody = str_replace("<a","<a style='color:#000;'",$temp_html);
		return $aBody;
	}

	//启动服务，未编码
	public function _start(){
		return true;
	}

	//停止服务，未编码
	public function _stop(){
		return true;
	}

	//安装服务，未编码
	public function _install(){
		return true;
	}

	//卸载服务，未编码
	public function _uninstall(){
		return true;
	}
}
?>